package ru.spb.osll.myfit.server.templateloader;

import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;

import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;
import ru.spb.osll.myfit.server.handler.PageLoader;
import ru.spb.osll.myfit.server.parser.PageParserUtils;
import ru.spb.osll.myfit.util.CollectionUtils;
import ru.spb.osll.myfit.wikiverifier.iterator.FileSystemIteratorListener;
import util.GracefulNamer;

public class TemplateLoaderFSIteratorListener implements
		FileSystemIteratorListener {
	private PageLoader m_loader;
	private HashMap<String, Vector<String>> m_templates;

	// FIXME
	public TemplateLoaderFSIteratorListener() {
		m_loader = new PageLoader("FitNesseRoot");
		m_templates = new HashMap<String, Vector<String>>();
	}

	public HashMap<String, Vector<String>> getTemplates() {
		return m_templates;
	}

	@Override
	public void listen(String filename) {
		try {
			String pagePath = filename.replaceAll("/", ".");
			pagePath = pagePath.replaceAll("\\", ".");
			Page page = m_loader.loadPage(filename, pagePath, null);
			for (PageElement elem : page.getElements()) {
				if (elem instanceof Table) {
					Table table = (Table) elem;
					if (table.getData().size() != 0) {
						Vector<String> rawTable = new Vector<String>(
								CollectionUtils.list(PageParserUtils
										.tableToString(table).split("\n")));
						m_templates.put(getClassName(table.getData().get(0)),
								rawTable);
					}
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void handleFinish() {
	}

	private String getClassName(Vector<TableCell> tableLine) {
		return GracefulNamer.disgrace(tableLine.get(0).getText());
	}
}
